﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;

namespace Gakita.Model.Enemies
{
    /* This class contains the logic for the FlyingEnemy. FlyingEnemies fly back and forth, occationally dropping a SpikyThing */
    class FlyingEnemy
    {
        private const float _distanceToTravel           =       17f;
        private const float _secondsBetweenDrops        =       1.5f;

        private float _secondsSinceLastDrop             =       0;
        private Vector2 _speed;
        private Vector2 _bottomCenterPosition;
        private Vector2 _startPosition;

        public FlyingEnemy(Vector2 aBottomCenterPosition, Vector2 aSpeed)
        {
            _speed = aSpeed;
            _bottomCenterPosition = aBottomCenterPosition;
            _startPosition = aBottomCenterPosition;
        }

        public void Update(float aElapsedTime, Level aLevel)
        {
            // To allow a Spiky Thing to be dropped every 1.5 seconds, we keep track of how long time has passed since it last dropped
            // a SpikyThing in the _secondsSinceLastDrop variable. If it's more then 1.5 seconds, a SpikyThing is spawned at the 
            // current location and the variable is reset.
            _secondsSinceLastDrop += aElapsedTime;

            if (_secondsSinceLastDrop > _secondsBetweenDrops)
            {
                aLevel._spikyThings.Add(new SpikyThing(_bottomCenterPosition, SpikyThing.Direction.FreeFalling));
                _secondsSinceLastDrop = 0;
            }

            // If the FlyingEnemy has moved a certain distance (specified in the _distanceToTravel variable), it will turn around.
            Vector2 nextPosition = _bottomCenterPosition + _speed * aElapsedTime;

            if (ItIsTimeToTurnAround())
            {
                TurnAround();
            }

            _bottomCenterPosition += _speed * aElapsedTime;
        }

        /* This method allow the FlyingEnemy to turn around, by reversing its' speed */
        private void TurnAround()
        {
            _speed.X = -_speed.X;
        }

        /* This method checks if the FlyingEnemy has moved too far away from it's starting position, and needs to turn around */
        private bool ItIsTimeToTurnAround()
        {
            if (_bottomCenterPosition.X > _startPosition.X + _distanceToTravel ||                                                                            _bottomCenterPosition.X < _startPosition.X - _distanceToTravel)
            {
                return true;
            }
            else
            {
                return false;
            }
        }


        public Vector2 GetPosition()
        {
            return _bottomCenterPosition;
        }
    }
}